import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import qs from "qs";
import {
  CommonResponseData,
  // respDataHandlerMap,
  // ResponseStatus,
} from "@/config/request/res-handler";

const networkService = axios.create({
  timeout: 20000,
});

// 请求拦截器
networkService.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 获取base url
    const baseURL = config.baseURL;
    if (!baseURL || baseURL.length === 0) {
      throw Promise.reject(new Error("请求base url请写在config中"));
    }

    // const respDataHandler = respDataHandlerMap.get(baseURL);

    // 本地环境去掉baseURL方便webpack dev server代理
    // issue: 接口跨域
    // const processConfig = process.env.CONFIG
    // if (processConfig.env === 'local') {
    //   config.baseURL = ''
    // }

    if (config.method === "get") {
      config.paramsSerializer = (params) => {
        return qs.stringify(params, { arrayFormat: "repeat" });
      };
    }

    // 标准化返回数据
    config.transformResponse = (data) => {
      let resultData = data;
      if (typeof data === "string") {
        resultData = JSON.parse(data);
      }
      // if (respDataHandler) {
      //   return respDataHandler(resultData);
      // }

      return resultData;
    };

    return config;
  },
  (error) => {
    throw error;
  }
);

// 响应拦截器
networkService.interceptors.response.use(
  (response: AxiosResponse) => {
    const res: CommonResponseData = response.data;
    return Promise.resolve(res);
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default networkService;
